import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl, AjaxJsonRpcFactory } from "pao-aop-client";

import React from "react";

import { addon, getObject, Ref } from "pao-aop";
import { Carousel, Icon, Tooltip } from "antd";

// import QRCode from 'qrcode.react';
// import qr from "qr-image";
import { SignAttribute, SignType, SelectCast, ModuleSort } from "src/models/baseSign";
import './index.less';
import { remote } from "../../clientAppConfig";
import { change_structure } from "../../app/util-tool";
import { IIndustryService } from "src/models/industry";
import { IProductTypeService } from "src/models/productType";

/**
 * 组件：标识预览状态
 */
export interface SignPreviewState extends BaseReactElementState {
    singleArray_packUp: boolean; // 展开收起判断
    categoryArray_packUp: boolean; // 展开收起判断
    companyArray_packUp: boolean; // 展开收起判断
    src: string; // 照片
    singleArray: any[]; // 单品
    singleHander: CollapseHeader;
    categoryArray: any[]; // 品类
    categoryHandle: CollapseHeader;
    companyArray: any[]; // 企业
    companyHandle: CollapseHeader;
    single_code: string;
    company_code: string;
    category_code: string;
    industry_name?: any;
    product_name?: any;
    Service_Fac?: Ref<IIndustryService>;
    pro_Service_Fac?: Ref<IProductTypeService>;
    /**
     * 决定排序对象数组
     */
    module_sort_arr?: any[];
}

export interface AnalysSinData {
    handle_code?: string;// 标识码
    handle_name?: string; // 标识名称
    attribute?: SignAttribute[]; // 标识属性
    image?: string; // 上传的照片
    module_sort?: ModuleSort; // 模块排序及是否显示对象
}

export interface CollapseHeader {
    handle_code?: string;// 标识码
    handle_name?: string; // 标识名称
    picture?: string[];
}

/**
 * 组件：标识预览
 * 描述 ：标识预览
 */
export class SignPreview extends BaseReactElement<SignPreviewControl, SignPreviewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            singleArray_packUp: true,
            categoryArray_packUp: true,
            companyArray_packUp: true,
            src: '',
            singleArray: [], // 单品
            singleHander: {},
            categoryArray: [], // 品类
            categoryHandle: {},
            companyArray: [],
            companyHandle: {},
            single_code: '',
            company_code: '',
            category_code: '',
            Service_Fac: new AjaxJsonRpcFactory(IIndustryService, remote.url, "IIndustryService"),
            pro_Service_Fac: new AjaxJsonRpcFactory(IProductTypeService, remote.url, "IProductTypeService")
        };
    }
    componentWillMount() {
        let data: AnalysSinData,
            singleArray: SignAttribute[] = [],
            singleHander: CollapseHeader = {},
            categoryArray: SignAttribute[] = [],
            categoryHandle: CollapseHeader = {},
            companyArray: SignAttribute[] = [],
            companyHandle: CollapseHeader = {};
        let exitItem = ["company_handle_code", "category_handle_code", "company_handle_name", "category_handle_name", "rc_code", "handle_type"];
        if (this.props.data) {
            data = this.props.data!;
            // /** 处理module_sort字段 */
            // const module_sort = data.module_sort;
            // let module_sort_arr = [];
            // if (module_sort) {
            //     if (module_sort.company && module_sort.company.is_show) {
            //         module_sort_arr.push({ name: 'company', show_sort: module_sort.company.show_sort });
            //     }
            //     if (module_sort.category && module_sort.category.is_show) {
            //         module_sort_arr.push({ name: 'category', show_sort: module_sort.category.show_sort });
            //     }
            //     if (module_sort.single && module_sort.single.is_show) {
            //         module_sort_arr.push({ name: 'single', show_sort: module_sort.single.show_sort });
            //     }
            //     module_sort_arr.sort((objectN: any, objectM: any) => {
            //         let valueN = objectN['show_sort'];
            //         let valueM = objectM['show_sort'];
            //         if (valueN < valueM) {
            //             return -1;
            //         } else if (valueN > valueM) {
            //             return 1;
            //         } else {
            //             return 0;
            //         }
            //     });
            // }
            // 处理类目项
            data.attribute!.sort((a: SignAttribute, b: SignAttribute) =>
                a.index - b.index
            );
            data.attribute!.forEach(item => {
                if (exitItem.includes(item.sign_key!)) {
                    return;
                }
                if (item.index && item.index > 99 && item.index < 200) {
                    if (item.sign_key === 'handle_name' || item.sign_key === 'handle_code' || item.sign_key === 'category_picture') {
                        categoryHandle[item.sign_key] = item.sign_value;
                    } else {
                        categoryArray.push(item);
                    }
                } else if (item.index && item.index < 300 && item.index > 199) {
                    if (item.sign_key === 'handle_name' || item.sign_key === 'handle_code' || item.sign_key === "product_picture") {
                        singleHander[item.sign_key] = item.sign_value;
                    } else {
                        singleArray.push(item);
                    }
                } else {
                    if (item.sign_key === 'handle_name' || item.sign_key === 'handle_code' || item.sign_key === "company_picture") {
                        companyHandle[item.sign_key] = item.sign_value;
                    } else {
                        companyArray.push(item);
                    }
                }
            });
            this.setState({ singleArray, singleHander, categoryArray, categoryHandle, companyArray, companyHandle }); // module_sort_arr
            this.dvertise_IProductTypeService!()!.then(
                e => {
                    let product_map = change_structure('industry_name', e!.result);
                    this.setState({ industry_name: product_map }
                    );
                });
            this.dvertise_Service!()!.then(
                e => {
                    let product_map = change_structure('product_type_name', e!.result);
                    this.setState({ product_name: product_map }
                    );
                });
        }
    }
    show(data: string) {
        if (data === 'singleArray_packUp') {
            return <div onClick={() => { this.setState({ singleArray_packUp: !this.state.singleArray_packUp }); }}>{this.state.singleArray_packUp ? <span style={{ fontWeight: 'bold', fontSize: 12 }}><Icon type="caret-up" />收起</span> : <span style={{ fontWeight: 'bold', fontSize: 12 }}><Icon type="caret-down" />展开</span>}</div>;
        } else if (data === 'categoryArray_packUp') {
            return <div onClick={() => { this.setState({ categoryArray_packUp: !this.state.categoryArray_packUp }); }}>{this.state.categoryArray_packUp ? <span style={{ fontWeight: 'bold', fontSize: 12 }}><Icon type="caret-up" />收起</span> : <span style={{ fontWeight: 'bold', fontSize: 12 }}><Icon type="caret-down" />展开</span>}</div>;
        } else {
            return <div onClick={() => { this.setState({ companyArray_packUp: !this.state.companyArray_packUp }); }}>{this.state.companyArray_packUp ? <span style={{ fontWeight: 'bold', fontSize: 12 }}><Icon type="caret-up" />收起</span> : <span style={{ fontWeight: 'bold', fontSize: 12 }}><Icon type="caret-down" />展开</span>}</div>;
        }
    }
    // 行业类型转换
    dvertise_IProductTypeService?() {
        return getObject(this.state.Service_Fac)!.get_industry_list!();
    }
    get_Industry(data?: any) {
        let industry = this.state.industry_name;
        if (data && industry) {

            return industry.get(data) ? industry.get(data) : data;
        }
    }
    get_Product(data?: any) {
        let industry = this.state.product_name;
        if (data && industry) {

            return industry.get(data) ? industry.get(data) : data;
        }

    }
    // 产品类型转换
    dvertise_Service?() {
        return getObject(this.state.pro_Service_Fac)!.get_product_type_list!();
    }
    // openLink = (link: string) => {
    //     alert(link);
    //     window.location.href = 'http://' + link;
    // }
    contentView(data: any[], header: any, check_pack_up: Boolean, sign: string, ) {
        // let signData=sign;
        let headerImg = header.category_picture || header.company_picture || header.product_picture;
        return (
            <div style={{ height: '100%', width: '100%', borderBottom: '10px solid rgba(245, 245, 245, 1)', background: 'white' }}>
                {
                    headerImg ? <Carousel autoplay={true}>
                        {
                            headerImg instanceof Array ?
                                headerImg.map((val: any, index: any) => {
                                    return (<div key={index + 1000} style={{ paddingLeft: 10, background: 'white' }}>
                                        <img src={val} style={{ width: '100%', padding: 10, background: 'white' }} />
                                    </div>);
                                })
                                : <div style={{ paddingLeft: 10, background: 'white' }}>
                                    <img src={headerImg} style={{ width: '100%' }} />
                                </div>
                        }
                    </Carousel>
                        : <div />}
                <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 10, background: "white" }}>

                    <div style={{ fontWeight: 'bold', display: 'flex', flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center' }}><span>{header.handle_name}</span>
                        {
                            sign === "singleArray_packUp" ?
                                null :
                                (<span style={{ marginLeft: 5, textAlign: 'center' }}>
                                    <Tooltip placement="topLeft" title={`标识码:${header.handle_code}`}>
                                        <img src={require('./img/rc_code.png')} />
                                    </Tooltip>
                                </span>)
                        }
                    </div>
                    {
                        this.show(sign)
                    }
                </div>
                {
                    check_pack_up &&
                    <div style={{ background: 'white', padding: 10, }}>
                        {
                            data!.map((item: any, idx: any) => {
                                if (item.sign_type === SignType.Text) {
                                    if (item.sign_key === 'custom_attribute') {
                                        return (item!.sign_value !== undefined && item!.sign_value.length > 0 ?
                                            item!.sign_value!.map((val: any, index: any) => {

                                                return (
                                                    // <div key={index} style={{ width: '100%', borderBottomWidth: 1, borderBottomStyle: 'solid', borderBottomColor: '#F4F2F2', padding: 14 }}>
                                                    <div key={item.sign_key + idx + Math.random()} className='com' >
                                                        {/* <span style={{ color: 'rgba(153, 153, 153, 1)' }}>{val.label}</span> */}
                                                        <div className='describe'>{val.label}</div>
                                                        {
                                                            SelectCast[val.format] === SignType.Image && val.value instanceof Array ?
                                                                val.value.map((item_val: any, item_index: any) => {
                                                                    return (<div key={item_index + 200} style={{ paddingLeft: 10 }}>
                                                                        <img src={item_val} style={{ width: '100%' }} />
                                                                    </div>
                                                                    );
                                                                })
                                                                :
                                                                // <span style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                                //     {val.value}
                                                                // </span>
                                                                <div className='details' dangerouslySetInnerHTML={{ __html: val.value ? val.value.replace(/\n|\r|\r\n/g, '<br />') : '' }} />
                                                        }
                                                        <div className="clearfix " />
                                                    </div>
                                                );
                                            }) : '');
                                    } else {
                                        if (item.sign_key === 'address') {
                                            return item.sign_value ?
                                                (
                                                    // <div key={idx} style={{ width: '100%', borderBottomWidth: 1, borderBottomStyle: 'solid', borderBottomColor: '#F4F2F2', padding: 14 }}>
                                                    <div key={item.sign_key + idx} className='com' >
                                                        {/* <span style={{ color: 'rgba(153, 153, 153, 1)' }}>{item.sign_name}</span> */}
                                                        <div className='describe'>{item.sign_name}</div>
                                                        {/* <span style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                        {item.sign_value.postData}
                                                    </span> */}
                                                        <div className='details'>
                                                            {`${item.sign_value.province}${item.sign_value.city}${item.sign_value.area}${item.sign_value.detail}`}
                                                        </div>
                                                        <div className="clearfix " />
                                                    </div>) : null;
                                        } else {
                                            return item.sign_value ?
                                                (
                                                    // <div key={idx} style={{ width: '100%', borderBottomWidth: 1, borderBottomStyle: 'solid', borderBottomColor: '#F4F2F2', padding: 14 }}>
                                                    <div key={item.sign_key + idx} className='com' >
                                                        {/* <span style={{ color: 'rgba(153, 153, 153, 1)' }}>{item.sign_name}</span> */}
                                                        <div className='describe'>{item.sign_name}</div>
                                                        {

                                                            item.sign_value! && item.sign_value! instanceof Array ?
                                                                item.sign_value!.map((val: any, index: any) => {

                                                                    if (item.sign_key !== 'email') {
                                                                        return (
                                                                            <div key={index + val}>
                                                                                <span style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                                                    {val.title}
                                                                                </span>
                                                                                <span style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                                                    {val.contents}
                                                                                </span>
                                                                            </div>);
                                                                    } else {
                                                                        return (<span key={index} style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                                            {val.title}
                                                                        </span>);

                                                                    }

                                                                })
                                                                :
                                                                (
                                                                    item.sign_key === 'website' ?
                                                                        <div className='details' >
                                                                            <a href={item.sign_value}>{item.sign_value}</a>
                                                                        </div>
                                                                        : <div
                                                                            className='details'
                                                                            dangerouslySetInnerHTML={{
                                                                                __html: item.sign_value && item.sign_key === "industry_type" ? this.get_Industry(item.sign_value) : (item.sign_value && item.sign_key === "product_type" ? this.get_Product(item.sign_value) : item.sign_value.replace(/\n|\r|\r\n/g, '<br/>'))
                                                                            }}
                                                                        />
                                                                )

                                                        }
                                                        <div className="clearfix " />
                                                    </div>
                                                ) : null;
                                        }
                                    }
                                } else if (item.sign_type === SignType.Image) {
                                    return item.sign_value ? (
                                        // <div key={idx} style={{ width: '100%', borderBottomWidth: 1, borderBottomStyle: 'solid', paddingBottom: 6, borderBottomColor: '#F4F2F2', paddingTop: 6, }}>
                                        <div key={item.sign_key + idx} className='com' >
                                            <span style={{ opacity: 0.6 }}>{item.sign_name}</span>
                                            <div>
                                                <Carousel autoplay={true}>
                                                    {
                                                        item.sign_value instanceof Array ?
                                                            item.sign_value.map((val: any, index: any) => {
                                                                return (<div key={index + 80} style={{ paddingLeft: 10 }}>
                                                                    <img src={val} style={{ width: '100%' }} />
                                                                </div>);
                                                            })
                                                            : <div style={{ paddingLeft: 10 }}>
                                                                <img src={item.sign_value} style={{ width: '100%' }} />
                                                            </div>
                                                    }
                                                </Carousel>
                                            </div>
                                        </div>
                                    ) : null;
                                } else if (item.sign_type === SignType.phone) {
                                    // <div key={idx} style={{ width: '100%', borderBottomWidth: 1, borderBottomStyle: 'solid', borderBottomColor: '#F4F2F2', padding: 14 }}>
                                    return item.sign_value ?
                                        (<div key={item.sign_key + idx} className='com' >
                                            {/* <span style={{ color: 'rgba(153, 153, 153, 1)' }}>{item.sign_name}</span> */}
                                            {/* <div className="fac_info_top">{item.sign_name}</div> */}
                                            {/* <span style={{ opacity: 0.6 }}>{item.sign_name}</span> */}
                                            <div className='describe'>{item.sign_name}</div>
                                            {

                                                item.sign_value! && item.sign_value! instanceof Array ?
                                                    item.sign_value!.map((val: any, index: any) => {
                                                        if (item.sign_key !== 'email') {
                                                            return (
                                                                <div className='details' key={index + 30}>
                                                                    {`${val.title} ${val.contents}`}
                                                                </div>
                                                            );
                                                            // <div className="fac_info_bottom">
                                                            //     {/* <span key={index} style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                            //             {val.title}
                                                            //         </span>
                                                            //         <span key={index} style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                            //             {val.contents}
                                                            //         </span> */}
                                                            //     <div key={index} className='describe'>
                                                            //         {val.title}
                                                            //     </div>
                                                            //     <div className='details'>
                                                            //         {val.contents}
                                                            //     </div>
                                                            // </div>);
                                                        } else {
                                                            return (
                                                                // <span key={index} style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                                //     {val.title}
                                                                // </span>
                                                                // <div className="fac_info_bottom">
                                                                <div className='details' key={val + index}>
                                                                    {val.title}
                                                                </div>
                                                            );

                                                        }

                                                    })
                                                    :
                                                    // <span style={{ color: "rgba(51, 51, 51, 1)", paddingLeft: 14 }}>
                                                    //     {item.sign_value! ? item.sign_value : ''}
                                                    // </span>
                                                    // <div className="fac_info_bottom">
                                                    <div className='details'>
                                                        {item.sign_value! ? item.sign_value : ''}
                                                    </div>

                                            }
                                            <div className="clearfix " />
                                        </div>) : null;
                                } else {
                                    return item.sign_value ?
                                        (
                                            // <div key={idx} style={{ width: '100%', borderBottomWidth: 1, borderBottomStyle: 'solid', borderBottomColor: '#F4F2F2', padding: 14 }}>
                                            <div key={item.sign_key + idx} className='com' >
                                                {/* <span style={{ color: 'rgba(153, 153, 153, 1)' }}>{item.sign_name}</span> */}
                                                {/* <div className="fac_info_top">{item.sign_name}</div> */}
                                                <div className="describe">{item.sign_name}</div>
                                                {
                                                    item.sign_value && item.sign_value instanceof Array ?
                                                        item.sign_value.map((val: any, index: any) => {
                                                            return (
                                                                // <div key={index} style={{ fontWeight: "bold", paddingLeft: 10 }}>
                                                                //     {val.title}
                                                                // </div>
                                                                // <div key={index} className="fac_info_bottom">
                                                                <div key={index + 20} className='details'>
                                                                    {val.title}
                                                                </div>
                                                                //      <div key={index} className="fac_info_bottom">
                                                                //      <div key={index} className='describe'>
                                                                //          {val.title}
                                                                //      </div>
                                                                //      <div className='details'>
                                                                //          {val.contents}
                                                                //      </div>
                                                                //  </div>
                                                            );
                                                        }) :
                                                        // <div style={{ fontWeight: "bold", paddingLeft: 10 }}>
                                                        //     {item.sign_value}
                                                        // </div>
                                                        // <div className="fac_info_bottom">
                                                        <div className='details'>
                                                            {item.sign_value}
                                                        </div>
                                                }
                                                <div className="clearfix " />
                                            </div>
                                        ) : null;
                                }
                            })
                        }

                    </div>
                }
            </div>
        );
    }
    callback = (key: any) => {
        console.log(key);
    }
    render() {
        let module_sort = this.state.module_sort_arr!;
        console.log(module_sort);
        return (
            <div style={{ background: '#F4F2F2' }}>
                {this.props.showCode ? <div>
                    <div style={{ textAlign: 'center', background: 'white', padding: 14, }}>
                        <div ><img style={{ width: '189px' }} src={require('./img/logo@3x.png')} /></div>
                        <div style={{ fontSize: '16px', fontWeight: 'bold', paddingTop: 14 }}><span style={{ marginLeft: 8 }}>工业互联网标识自助服务平台</span></div>
                        <div style={{ marginTop: 10, borderTop: '1px solid rgba(229, 229, 229, 1)' }} />
                        <div style={{ fontSize: 12, paddingTop: 8 }}>
                            <span >标识码：</span>
                            <span style={{ wordWrap: 'break-word' }}>{this.props.data! ? this.props.data!.handle_code : ''}</span>
                        </div>
                    </div>
                    <div style={{ marginTop: 10, background: 'white', textAlign: 'center', width: '100%' }}>
                        {this.props.data === undefined || this.props.data!.image! === undefined ? '' : (<img src={this.props.data!.image!} style={{ width: '100%', height: 'auto' }} />)}
                    </div>
                    {
                        // (() => {
                        // if (module_sort) {
                        module_sort!.map(item => {
                            if (item.name === 'single' && this.state.singleArray.length > 0) {
                                return this.contentView(this.state.singleArray, this.state.singleHander, this.state.singleArray_packUp, 'singleArray_packUp');
                            } else if (item.name === 'company' && this.state.companyArray.length > 0) {
                                return this.contentView(this.state.companyArray, this.state.companyHandle, this.state.companyArray_packUp, 'companyArray_packUp');
                            } else if (item.name === 'category' && this.state.categoryArray.length > 0) {
                                return this.contentView(this.state.categoryArray, this.state.categoryHandle, this.state.categoryArray_packUp, 'categoryArray_packUp');
                            } else {
                                return <div />;
                            }
                        })
                        // }
                        // })()
                    }
                    {
                        module_sort.length === 0 && this.state.categoryArray.length > 0 ? this.contentView(this.state.categoryArray, this.state.categoryHandle, this.state.categoryArray_packUp, 'categoryArray_packUp') : <div />
                    }
                    {
                        module_sort.length === 0 && this.state.singleArray.length > 0 ? this.contentView(this.state.singleArray, this.state.singleHander, this.state.singleArray_packUp, 'singleArray_packUp') : <div />
                    }
                    {
                        module_sort.length === 0 && this.state.companyArray.length > 0 ? this.contentView(this.state.companyArray, this.state.companyHandle, this.state.companyArray_packUp, 'companyArray_packUp') : <div />
                    }
                </div> : <div style={{ width: '100%', minHeight: 400, justifyContent: 'center', alignItems: 'center', background: 'white', display: 'flex' }}><img style={{ height: '200px', width: 'auto' }} src={this.props.qr_code} /></div>
                }
            </div>
        );
    }
}

/**
 * 控件：标识预览控制器
 * 描述
 */
@addon('SignPreview', '标识预览', '标识预览')
@reactControl(SignPreview)
export class SignPreviewControl extends BaseReactElementControl {
    /**
     * 数据源
     */
    data?: AnalysSinData;
    showCode?: boolean;
    qr_code?: string;
    constructor() {
        super();
    }
}